package com.socket.tools.config;

import com.socket.tools.websocket.WebSocketHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean;

/**
 * WebSocket配置
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
    
    @Autowired
    private WebSocketHandler webSocketHandler;
    
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(webSocketHandler, "/ws")
                .setAllowedOriginPatterns("*") // 允许所有来源，生产环境应该限制
                .withSockJS(); // 启用SockJS支持
    }
    
    /**
     * WebSocket连接池配置
     */
    @Bean
    public ServletServerContainerFactoryBean createWebSocketContainer() {
        ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
        
        // 设置最大文本消息大小 (1MB)
        container.setMaxTextMessageBufferSize(1024 * 1024);
        
        // 设置最大二进制消息大小 (1MB)
        container.setMaxBinaryMessageBufferSize(1024 * 1024);
        
        // 设置空闲超时时间 (5分钟)
        container.setMaxSessionIdleTimeout(300000L);
        
        // 设置异步发送超时时间 (10秒)
        container.setAsyncSendTimeout(10000L);
        
        return container;
    }
} 